<template>
  <div ref="imageWrapper">
    <a-card class="search" title="查询条件">
      <!-- 查询区域 -->
      <div class="table-page-search-wrapper">
        <a-form-model ref="ruleForm" :model="queryParam" :rules="rules" layout="inline" @keyup.enter.native="onSearch">
          <a-row :gutter="24">
            <a-col :md="5" :sm="6">
              <a-form-model-item label="审计项目名称" prop="projectname">
                <a-input
                  placeholder="请选择审计单位名称"
                  v-model="queryParam.projectname"
                  readOnly
                  @click.native="openSearchModel"
                ></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :md="5" :sm="6">
              <a-form-model-item label="账套/核算单元" prop="accName">
                <a-input
                  v-model="queryParam.accName"
                  readOnly
                  placeholder="请选择账套/核算单元"
                  @click.native="openOrganModel"
                />
              </a-form-model-item>
            </a-col>
            <a-col :md="5" :sm="6">
              <a-form-model-item label="工程项目" prop="proId">
                <a-input v-model="queryParam.proId" placeholder="请选择工程项目" />
              </a-form-model-item>
            </a-col>
            <a-col :md="5" :sm="6">
              <a-form-model-item label="审计期间" prop="arrayTime">
                <a-range-picker
                  v-model="queryParam.arrayTime"
                  format="yyyy-MM-DD"
                  value-format="yyyy-MM-DD"
                  @change="handleDatechange"
                />
              </a-form-model-item>
            </a-col>
            <a-col :md="4" :sm="6">
              <span style="float: right" class="table-page-search-submitButtons">
                <a-button
                  @click="onRun"
                  class="yellow_search_btn"
                  style="color: white; margin-left: 18px; font-size: 700"
                >
                  一键成稿
                </a-button>
                <a-button type="primary" style="margin-left: 18px" @click="backUppage">返回</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
    </a-card>
    <a-row class="model-body">
      <a-col :md="5" :sm="24" style="height: calc(100vh - 350px)">
        <a-card class="card-radius" style="overflow-x: scroll">
          <template slot="title">
            <span style="color: #2e4cba">分类选择</span>
          </template>
          <a-spin size="large" class="card-item-loding1" :spinning="loading1" v-show="loading1" />
          <SideMenuOnPage :disabled="true" :menuitem="reportList" @menuItenId="queryParam.id = $event" />
        </a-card>
      </a-col>
      <a-col :md="19" :sm="24" style="height: calc(100vh - 350px)">
        <a-card class="card-radius">
          <div slot="title" style="display: flex; justify-content: space-between">
            <span style="color: #2e4cba">已选择{{ selectarr.length }}个模型，总共{{ total }}个模型</span>
            <a-checkbox @change="onChange"><span style="color: #2e4cba">全选</span></a-checkbox>
          </div>
          <a-spin size="large" class="card-item-loding" :spinning="loading" v-show="loading" />
          <div v-show="!loading" class="card-item-content">
            <BaseDatilebox
              v-for="item in dataSource"
              :key="item.id"
              :boxTitle="item"
              :checked="checkisSelected(item.id)"
              @checkfxzb="checkAnalysisIndex"
              @handleSelected="handleSelected"
            >
              <template v-slot:boxContent>
                <p>
                  分&emsp;&emsp;类：
                  <a-tooltip placement="topLeft" overlayClassName="bgc_tooltip1">
                    <template slot="title">
                      <span>{{ item.pmodelName }}</span>
                    </template>
                    <span class="item-content-b box-card-subtitle">{{ item.pmodelName }}</span>
                  </a-tooltip>
                  <!-- <j-ellipsis :value="item.pmodelName" :length="8" /> -->
                </p>
                <p class="analyzeResult">
                  模型描述：
                  <a-tooltip placement="topLeft" overlayClassName="bgc_tooltip1">
                    <template slot="title">
                      <span>{{ item.mxms }}</span>
                    </template>
                    <span class="item-content-b">{{ item.mxms }}</span>
                  </a-tooltip>
                </p>
              </template>
            </BaseDatilebox>
          </div>
        </a-card>
      </a-col>
    </a-row>
    <CheckOrganModal ref="departModal" @ok="updateQueryParam" />
    <AnalysisIndex ref="AnalysisIndex" @save="editIndicator" />
    <ProjectModel ref="projectModal" @getSelect="getProId" />
  </div>
</template>

<script>
import { httpAction, getAction, postAction, putAction } from '@/api/manage'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import CheckOrganModal from '../../../../sjxmzygl/yzzx/testcomponent/CheckOrganModal'
import BaseDatilebox from '../BaseDatilebox'
import AnalysisIndex from '../CheckModel'
import SideMenuOnPage from '../SideMenuOnPage'
import ProjectModel from './ProjectModel.vue'
export default {
  name: 'DraftGenerator',
  mixins: [JeecgListMixin],
  components: { BaseDatilebox, CheckOrganModal, AnalysisIndex, SideMenuOnPage, ProjectModel },
  props: ['record', 'returnRouterPage', 'returnRecord'],
  data() {
    return {
      visible: false,
      isactive: true,
      dataSource: [],
      reportList: [],
      superQueryParams: {},
      queryParam: {
        id: '0',
        projectId: '',
        projectname: undefined,
        accName: ''
      },
      modelId: '',
      total: 0,
      loading: false,
      loading1: false,
      url: {
        detailBox: '/sjmx/queryDataModel',
        add: '/sjmx/sjZxzyQuickDraft/add',
        create: 'sjmx/createQuickDraft',
        queryModelField: '/sjmx/sjModelFieldConfig/queryModelField',

        editIndicator: '/sjmx/sjModelFieldConfig/edit'
      },
      selectarr: [],
      rules: {
        projectname: [{ required: true, message: '不能为空!' }],
        accName: [{ required: true, message: '不能为空!' }],
        arrayTime: [{ required: true, message: '不能为空!' }]
      },
      disableMixinCreated: true
    }
  },
  mounted() {
    // 生成左侧菜单
    this.getReportList()
    this.getDetailBox('0')
  },
  watch: {
    'queryParam.id'(val) {
      this.getDetailBox(val)
    },
    // 从别的地方跳过来
    record: {
      handler(val) {
        console.log('val------------------>', val)
        if (Object.keys(val).length) {
          let { accCode, accName, id, name, startDate, endDate } = val
          this.queryParam.accName = accName
          this.queryParam.accCode = accCode
          this.queryParam.startTime = startDate
          this.queryParam.endTime = endDate
          this.queryParam.arrayTime = [startDate, endDate]
          this.queryParam.projectId = id
          this.queryParam.projectname = name
        }
      },
      immediate: true
    }
  },
  methods: {
    onRun() {
      if (this.selectarr.length == 0) return this.$message.warning('请选择模型')
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          // 创建任务
          await this.createTask()
          await this.createQuickDraft()
          this.$emit('CheckGenerateResult', { id: this.modelId })
        }
      })
    },
    backUppage() {
      // 如果不是路由调过来的，就是普通的返回
      if (!this.returnRouterPage) {
        this.$emit('BackFristPage')
      } else {
        // 返回对应的路由页
        this.$router.push({
          path: '/sjxmzygl/sjxmss',
          query: {
            record: this.returnRecord,
            // 返回调转到审计底稿
            activeKey: 'sssj',
            activeValue: '审计分工',
            activeMenu: 'sjdg'
          }
        })
      }
    },
    onChange({ target: { checked } }) {
      let allArr = []
      let selectArr = []
      if (checked) {
        this.dataSource.map(item => {
          allArr.push(item.id)
        })
        selectArr = JSON.parse(JSON.stringify(this.selectarr))
        let a = selectArr.concat(allArr)
        this.selectarr = []
        this.selectarr = Array.from(new Set(a))
      } else {
        this.selectarr = []
      }
    },
    close() {
      this.visible = false
    },
    // checkbox处理选中
    handleSelected(id, isSelected) {
      if (isSelected) {
        if (this.selectarr.indexOf(id) == -1) this.selectarr.push(id)
      } else {
        this.selectarr = this.selectarr.filter(item => {
          return !(item == id)
        })
      }
      console.log(this.selectarr)
    },
    // 检查这个box-id是否被选中
    checkisSelected(id) {
      console.log(this.selectarr.indexOf(id))
      return this.selectarr.indexOf(id) != -1
    },
    checkAnalysisIndex(modelId) {
      getAction(this.url.queryModelField, { modelId }).then(res => {
        if (res.success) {
          let data = JSON.parse(res.result && res.result.projectJson)
          this.$refs.AnalysisIndex.edit(data, modelId, res.result.modelType)
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    handleDatechange(dates) {
      this.queryParam.startTime = dates[0]
      this.queryParam.endTime = dates[1]
    },
    // 保存已经修改的projectJson(子组件返回json串)
    editIndicator(projectJson, modelId) {
      putAction(this.url.editIndicator, { projectJson, modelId }).then(res => {
        console.log(res)
      })
    },
    // handleClick({ item, key, keyPath }) {
    //   console.log('')
    //   this.queryParam.tableName = ''
    //   this.queryParam.reportCategoryId = key
    //   this.getDetailBox(1)
    // },
    openSearchModel() {
      this.$refs.projectModal.show()
    },
    getProId(project) {
      this.queryParam.projectId = project.id
      this.queryParam.projectname = project.name
    },
    getDetailBox(val) {
      this.loading = true
      getAction(this.url.detailBox, { id: val }).then(res => {
        if (res.success) {
          this.dataSource = res.result
          if (this.queryParam.id == '0') this.total = res.result.length
        }
        this.loading = false
      })
    },
    getReportList() {
      this.loading1 = true
      getAction(this.url.detailBox).then(res => {
        if (res.success && res.result.length > 0) {
          this.reportList = res.result
        } else {
          console.log(res)
        }
        this.loading1 = false
      })
    },
    //执行  -- 一键成稿
    createQuickDraft() {
      return new Promise((reslove, reject) => {
        this.loading = true
        let params = Object.assign({ modelIdList: this.selectarr.join(',') }, this.queryParam)
        params.id = this.modelId
        getAction(this.url.create, params).then(res => {
          this.loading = false
          if (res.success) {
            this.$message.success(res.message)
          } else {
            this.$message.warning(res.message)
          }
          reslove()
        })
      })
    },
    createTask() {
      return new Promise((reslove, reject) => {
        postAction(this.url.add, { progressStatus: 1 }).then(res => {
          if (res.success) {
            this.modelId = res.result
          } else {
            this.modelId = ''
            this.$message.error(res.message)
            this.$emit('BackFristPage')
          }
          reslove()
        })
      })
    },
    openOrganModel() {
      this.$refs.departModal.edit()
    },
    updateQueryParam(data, orgId, midId, midName) {
      debugger
      let str1 = ''
      let str2 = ''
      let str3 = ''
      data.map(item => {
        // TODO 账套～～～
        str1 += item.unitId + ','
        str2 += item.accName + ','
        str3 += item.accCode + ','
      })
      if (str1.length > 0) {
        str1 = str1.substr(0, str1.length - 1)
      }
      if (str2.length > 0) {
        str2 = str2.substr(0, str2.length - 1)
      }
      if (str3.length > 0) {
        str3 = str3.substr(0, str3.length - 1)
      }
      this.queryParam.unitId = str1
      this.queryParam.accName = str2 ? str2 : midName
      this.queryParam.accCode = str3
      this.superQueryParams.extraId = str2
      this.queryParam.orgId = midId
    }
  }
}
</script>
<style lang="less" scoped>
@import '~@assets/less/tableTheme.less';
.ant-table-fixed-left .ant-table-thead > tr > th:last-child {
  border-top-right-radius: 0;
  background-color: red;
  padding: 0;
}
.model-body {
  margin: 20px 0 0 0 !important;
  /deep/ .ant-card-body {
    padding: 0px 20px;
    position: relative;
    height: calc(100vh - 350px);
    .card-item-loding {
      position: absolute;
      top: 45%;
      left: 48%;
    }
  }
  /deep/ .ant-input-group {
    /deep/ .ant-input-group-addon {
      /deep/ .ant-btn-primary {
        background-color: #fff;
        border-color: #fff;
      }
    }
  }
  .card-item-content {
    width: 100%;
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    height: 100%;
    overflow-x: scroll;
  }
}
.baseDatilebox {
  height: 220px;
}
</style>
